import { Component } from 'react';
import Taro from '@tarojs/taro';
import { enableAkitaProdMode, persistState, PersistStateSelectFn } from '@datorama/akita';

import CONFIG from '@/config';
import { makeFacade } from '@/facade/messageFacade';
import { getLogger } from '@/utils/log';
import { Auth } from '@/models/Auth';
import { Message } from '@/models/Message';
import '@/app.scss';

class App extends Component {
  componentWillMount() {
    Taro.setTabBarStyle({
      color: "#333333",
      selectedColor: MAIN_COLOR, // 选中时的色号
    })
    Taro.setTabBarItem({
      index: 0,
      text: "首页",
      iconPath: ASSETS_PATH + "/index.png",
      selectedIconPath: ASSETS_PATH + "/index_b.png",
    })
    Taro.setTabBarItem({
      index: 1,
      text: "我的",
      iconPath: ASSETS_PATH + "/my.png",
      selectedIconPath: ASSETS_PATH + "/my_b.png",
    })

    const miniProgramUpdateManager = Taro.getUpdateManager();
    // 此处用if是因为有可能报以下错误: TypeError: undefined is not an object (evaluating \'V.onCheckForUpdate\')
    if (miniProgramUpdateManager) {
      miniProgramUpdateManager.onCheckForUpdate(res => res.hasUpdate && Taro.showToast({ title: '新版本下载中...' }));

      miniProgramUpdateManager.onUpdateReady(() => {
        Taro.showModal({
          title: '更新提示',
          content: '新版本已经准备好，立马体验新功能？',
          success: res => res.confirm && miniProgramUpdateManager.applyUpdate()
        })
      })

      miniProgramUpdateManager.onUpdateFailed(() => {
        // 新的版本下载失败
        Taro.showToast({ title: '新版本下载失败...', icon: 'none' })
      })
    }

    // 配置akita产品状态
    if (CONFIG.ENV === "production") enableAkitaProdMode();
    //云开发初始化
    if (process.env.TARO_ENV === 'weapp') {
      //云数据库初始化
      if (!Taro.cloud) {
        this.logger.ERROR('请使用 2.2.3 或以上的基础库以使用云能力')
      } else {
        Taro.cloud.init({
          env: CONFIG.WXCLOUD_CONF.ENV,
          traceUser: true
        })
      }
    }

    // 定义需要持久化到localstorage的字段
    const selectAuth: PersistStateSelectFn<Auth> = (state) => ({ userId: state.userId, token: state.token, refresh_token: state.refresh_token, roles: state.roles, orgs: state.orgs });
    selectAuth.storeName = 'auth';

    const selectTIM: PersistStateSelectFn<Message> = (state) => ({ isSDKReady: state.isSDKReady });
    selectTIM.storeName = 'tim';

    // 把特定store或者内部值持久化到本地存储
    persistState({
      include: [selectAuth.storeName],
      select: [selectAuth],
      enableInNonBrowser: true,
      // preStorageUpdateOperator: () => debounceTime(50),
      //以下自定义存储实现支持小程序和H5
      storage: {
        getItem: (key: string) => {
          return Taro.getStorageSync(key)
        },
        setItem: (key: string, data: any) => {
          return Taro.setStorageSync(key, data);
        },
        clear: () => {
          Taro.clearStorage();
        }
      }
    })

    //提前初始化IM绑定
    this.msgFacade.bindOn();
  }

  // componentDidMount() {}

  // componentDidShow () {}

  // componentDidHide () {}

  // componentDidCatchError () {}

  msgFacade = makeFacade();

  logger = getLogger("/app");

  // this.props.children 是将要会渲染的页面
  render(): React.ReactNode {
    return this.props.children
  }
}

export default App
